package com.hetwen.search.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;

import com.hetwen.search.R;
import com.hetwen.search.activity.base.BaseActivity;
import com.hetwen.search.face.DetectCallback;
import com.hetwen.search.face.FaceDetector;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.laiwang.controller.UMLWHandler;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.RenrenSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.yixin.controller.UMYXHandler;

public class ImageActivity extends BaseActivity {

	private PhotoView mPhotoView;
	protected PhotoViewAttacher attacher;
	private FaceDetector detector;
	private Bitmap image;
	private String target;
	private String url;
	private UMSocialService mController;

	@Override
	protected void loadView() {
		setContentView(R.layout.activity_image);
	}

	@Override
	protected void initView() {
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		mPhotoView = (PhotoView) findViewById(R.id.activity_image_photo_view);
		attacher = new PhotoViewAttacher(mPhotoView);
	}

	@Override
	protected void initData() {
		configPlatforms();

		target = Environment.getExternalStorageDirectory().getPath()
				+ "/tmp.img";

		Intent intent = getIntent();
		url = intent.getStringExtra("url");

		detector = new FaceDetector();
		detector.setDetectCallback(new DetectCallback() {
			@Override
			public void detectResult(Bitmap img) {
				image = img;
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mPhotoView.setImageBitmap(image);
					}
				});
			}
		});

		showLoadingDialog();
		downloadImage(url, new DownloadCallback() {

			@Override
			public void onSuccess() {
				closeLoadingDialog();
				mPhotoView.setImageBitmap(image);
			}

			@Override
			public void onFailure() {
				closeLoadingDialog();
			}
		});
	}

	private void configPlatforms() {
		mController = UMServiceFactory.getUMSocialService("com.umeng.share");
		// 添加新浪SSO授权
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		// 添加腾讯微博SSO授权
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
		// 添加人人网SSO授权
		RenrenSsoHandler renrenSsoHandler = new RenrenSsoHandler(mActivity,
				"201874", "28401c0964f04a72a14c812d6132fcef",
				"3bf66e42db1e4fa9829b955cc300b737");
		mController.getConfig().setSsoHandler(renrenSsoHandler);

		// 添加QQ、QZone平台
		addQQQZonePlatform();

		// 添加微信、微信朋友圈平台
		addWXPlatform();
	}

	/**
	 * 添加QQ空间平台
	 */
	private void addQQQZonePlatform() {
		String appId = "100424468";
		String appKey = "c7394704798a158208a74ab60104f0ba";
		// 添加QQ支持, 并且设置QQ分享内容的target url
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(mActivity, appId,
				appKey);
		qqSsoHandler.setTargetUrl("http://www.umeng.com/social");
		qqSsoHandler.addToSocialSDK();

		// 添加QZone平台
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(mActivity, appId,
				appKey);
		qZoneSsoHandler.addToSocialSDK();
	}

	/**
	 * 添加微信平台
	 */
	private void addWXPlatform() {
		// 注意：在微信授权的时候，必须传递appSecret
		// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
		String appId = "wx967daebe835fbeac";
		String appSecret = "5bb696d9ccd75a38c8a0bfe0675559b3";
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(mActivity, appId, appSecret);
		wxHandler.addToSocialSDK();

		// 支持微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(mActivity, appId,
				appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
	}

	/**
	 * 添加来往和来往动态平台
	 */
	protected void addLaiWang() {

		String appToken = "laiwangd497e70d4";
		String secretID = "d497e70d4c3e4efeab1381476bac4c5e";
		// laiwangd497e70d4:来往appToken,d497e70d4c3e4efeab1381476bac4c5e:来往secretID
		// 添加来往的支持
		UMLWHandler umlwHandler = new UMLWHandler(mActivity, appToken, secretID);
		umlwHandler.addToSocialSDK();

		// 添加来往动态的支持
		UMLWHandler lwDynamicHandler = new UMLWHandler(mActivity, appToken,
				secretID);
		lwDynamicHandler.setToCircle(true);
		lwDynamicHandler.addToSocialSDK();
	}

	/**
	 * 添加易信平台
	 */
	protected void addYXPlatform() {
		// 添加易信平台
		UMYXHandler yixinHandler = new UMYXHandler(mActivity,
				"yxc0614e80c9304c11b0391514d09f13bf");
		// 关闭分享时的等待Dialog
		yixinHandler.enableLoadingDialog(false);
		// 设置target Url, 必须以http或者https开头
		yixinHandler.setTargetUrl("http://www.umeng.com/social");
		yixinHandler.addToSocialSDK();

		// 易信朋友圈平台
		UMYXHandler yxCircleHandler = new UMYXHandler(mActivity,
				"yxc0614e80c9304c11b0391514d09f13bf");
		yxCircleHandler.setToCircle(true);
		yxCircleHandler.addToSocialSDK();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.image, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		if (itemId == android.R.id.home) {
			finish();
			return true;
		}
		if (itemId == R.id.action_share) {
			shareImage();
			return true;
		}
		return true;
	}

	/**
	 * 分享图片
	 */
	private void shareImage() {
		// 设置分享内容
		mController.setShareContent("这是测试分享图片" + url);
		mController.setShareMedia(new UMImage(mContext, url));

		mController.openShare(mActivity, false);
	}

	private void downloadImage(final String url, final DownloadCallback callback) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				HttpUtils http = new HttpUtils();
				http.download(url, target, new RequestCallBack<File>() {

					@Override
					public void onSuccess(ResponseInfo<File> response) {
						logger.i(mTag, "onSuccess");
						try {
							File file = response.result;
							Bitmap bitmap = BitmapFactory
									.decodeStream(new FileInputStream(file));
							image = bitmap;
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									callback.onSuccess();
								}
							});
							detector.detect(bitmap);
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException e, String error) {
						logger.i(mTag, "onFailure:" + error);
					}
				});
			}
		}).start();

	}

	public interface DownloadCallback {
		public void onSuccess();

		public void onFailure();
	}

}
